/*
  Copyright (c) 2009, Pablo Davi Faria da Silva
  Novesfora.com.br
  Blog.des84.com
  All rights reserved.

  Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright notice, 
    this list of conditions and the following disclaimer.
  
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the 
    documentation and/or other materials provided with the distribution.
  
  * Neither the name of Novesfora, DES84 nor the names of its 
    contributors may be used to endorse or promote products derived from 
    this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package Born.images
{
	import com.adobe.images.JPGEncoder;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.net.navigateToURL;
	import flash.utils.ByteArray;

	public class PSDExport extends Sprite
	{
		private var fr:FileReference;
		private var ba:ByteArray;
		private var newButtom:MovieClip;
		private var downloadFile:String;
		private var filename:String;
		
		public function PSDExport()
		{
			// nothing
		}
		
		public function chooseFile(m:MovieClip):void
		{
			newButtom = m;
			newButtom.addEventListener(MouseEvent.CLICK, init);
		}
		
		public function fileName(s:String):void
		{
			filename = s;
		}
		
		public function downloadURL(url:String):void
		{
			downloadFile = url;
		}
		
		private function init(e:MouseEvent):void
		{
			if ( filename == null ) filename = "exportImage";
			if ( downloadFile == null ) downloadFile = "downloadFile.php";
			
			fr = new FileReference();
			fr.addEventListener(Event.COMPLETE, onComplete);
			fr.addEventListener(Event.SELECT, function():void{fr.load();});
			fr.browse();
		}
		
		private function onComplete(e:Event):void
		{
			ba = fr.data as ByteArray;
			parsePSD();
		}
		
		private function parsePSD():void
		{
			// READ HEADER
			ba.position = 14;
			var height:int = ba.readInt();
			var width:int = ba.readInt();
			ba.position += 4;
			
			// COLOR DATA
			var len:int = ba.readInt();
			ba.position += len;
			
			// IMAGE RESOURCES
			len = ba.readInt();
			ba.position += len;
			
			// LAYERS AND MASKS
			len = ba.readInt();
			ba.position += len;
			
			ba.position += 2;
			
			var counts:Vector.<int> = new Vector.<int>(height*3, true);			
			var i:int;
			
			// GET THE BYTE COUNTS FOR ALL LINES
			for(i=0; i<height*3; ++i)
			{
				counts[i] = ba.readUnsignedShort();			
			}
			
			var r:ByteArray = new ByteArray();
			var g:ByteArray = new ByteArray();
			var b:ByteArray = new ByteArray();
			var line:ByteArray;
			
			// EXTRACT THE RED CHANNELS
			for(i=0; i<height; ++i)
			{
				line = new ByteArray();
				ba.readBytes(line, 0, counts[i]);
				r.writeBytes(uncompress(line)); 		
			}	
			
			// EXTRACT THE GREEN CHANNELS
			for(i=0; i<height; ++i)
			{
				line = new ByteArray();
				ba.readBytes(line, 0, counts[height+i]);
				g.writeBytes(uncompress(line)); 		
			}	
			
			// EXTRACT THE BLUE CHANNELS
			for(i=0; i<height; ++i)
			{
				line = new ByteArray();
				ba.readBytes(line, 0, counts[2*height+i]);
				b.writeBytes(uncompress(line)); 		
			}				
			
			var bmd:BitmapData = new BitmapData(width, height);

			r.position = 0;
			g.position = 0;
			b.position = 0;
			
			for(var y:int=0; y<height; ++y)
			{
				for(var x:int=0; x<width; ++x)
				{
					bmd.setPixel(x, y, r.readUnsignedByte()<<16 | g.readUnsignedByte()<<8 | b.readUnsignedByte());
				}			
			}	
			
			var bm:Bitmap = new Bitmap(bmd);
			bm.x = 0;
			bm.y = 0;
			
			sendToDownload(bm);
		}
		
		// EDITED PART TO CREATE ONE JPEG FILE AND EXPORT
		private function sendToDownload(bit:Bitmap):void
		{
			var newPrint:MovieClip = new MovieClip();
				newPrint.addChild(bit);
				
			var newJPG:BitmapData = new BitmapData(newPrint.width,newPrint.height);
				newJPG.draw(newPrint);
				
			var newJPGEncoder:JPGEncoder = new JPGEncoder(90);
			var newByteArray:ByteArray = newJPGEncoder.encode(newJPG);
			var newHeader:URLRequestHeader = new URLRequestHeader ("Content-type", "application/octet-stream");
			var jpgURLRequest:URLRequest = new URLRequest (downloadFile + "?name=" + filename + ".jpg");		
				jpgURLRequest.requestHeaders.push(newHeader);
				jpgURLRequest.method = URLRequestMethod.POST;
				jpgURLRequest.data = newByteArray;
					
			navigateToURL(jpgURLRequest, "_blank");
		}
		
		//EXPANDS THE PACKBITS RLE COMPRESSION 
		private function uncompress(b:ByteArray):ByteArray
		{
			var n:int;
			var count:int;
			var byte:int;
			var i:int;
			var rb:ByteArray = new ByteArray();
			
			while(b.bytesAvailable)
			{
				n = b.readByte();
				if(n >= 0)
				{
					count = n+1;
					for(i=0; i<count; ++i)
					{
						rb.writeByte(b.readByte());
					}
				}
				else
				{
					byte = b.readByte();
					count = 1 - n;
					for(i=0; i<count; ++i)
					{
						rb.writeByte(byte);
					}
				}
			}
			return rb;
		}
	}
}